<?php

$dbh    = null;
$db_map = array();

define('RIP_RESERVED', 0);
define('RIP_CREATE',   'create');
define('RIP_READ',     'read');
define('RIP_UPDATE',   'update');
define('RIP_DELETE',   'delete');


// DATABASE functions

function rip_setup_db() {
  global $dbh, $config;

  $db = $config['database'];

  try {
    watchdog(t('Setting up the database'), WATCHDOG_INFO);
    $dbh = new PDO(
      akh_get($db, 'driver',   'mysql')     . ':host='   .
      akh_get($db, 'host',     'localhost') . ';dbname=' .
      akh_get($db, 'dbname',   'test'),
      akh_get($db, 'username', 'root'),
      akh_get($db, 'password', ''),
      akh_get($db, 'options',  array())
    );
  } catch (PDOException $e) {
    watchdog(t('Error while connecting to the database'), WATCHDOG_ERROR);
    exit(WATCHDOG_ERROR);
  }
}

function rip_map_db() {
  global $dbh, $db_map;

  $result = $dbh->query('SHOW TABLES', PDO::FETCH_COLUMN, 0);

  foreach ($result as $k => $v) {
    $db_map[] = $v;
  }
}

function rip_teardown_db() {
  global $dbh;

  watchdog(t('Tearing down the database'), WATCHDOG_INFO);
  unset($dbh);
}

function rip_prepare_query($query_type, $uri) {
  $table_name = akh_get_recursive($uri, array('path', 'resource'), 'core');

  if (rip_load_module($table_name) && rip_check_module_action($table_name, $query_type)) {
    return call_user_func($table_name . '_' . $query_type . '_prepare', $uri);
  } else {
    rip_load_module('core');
    return call_user_func('core_' . $query_type . '_prepare', $uri);
  }
}

function rip_prepare_query_params($uri) {
  return array_values(
    array_merge(
      akh_get_recursive($uri, array('path', 'identifier'), array()),
      akh_get($uri, 'query', array())
    )
  );
}


// MODULES-related functions

function rip_load_module($module_name) {
  $module_path = RIP_ROOT_FOLDER . RIP_DIRECTORY_MODULES . $module_name . '.php';

  return file_exists($module_path) ? @include_once $module_path : false;
}

function rip_check_module_action($module_name, $action) {
  return function_exists($module_name . '_' . $action);
}


// PATH REWRITING functions

function rip_set_rewrite_rules() {

}

function rip_get_rewrite_rules() {

}

function rip_add_rewrite_rule() {

}

function rip_del_rewrite_rule() {

}


// CRUD base functions

function rip_create() {

}

function rip_read($uri) {
  global $dbh;

  $q = rip_prepare_query(RIP_READ, $uri);
  $stmt = $dbh->prepare($q);

  $p = rip_prepare_query_params($uri); 
  if ($stmt->execute($p)) {
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  } else {
    $rows = array();
    var_dump($stmt->errorCode());
    var_dump($stmt->errorInfo());
  }

  return $rows;
}

function rip_update() {

}

function rip_delete() {

}


// UTILITY functions

function rip_parse_uri() {
  $uri = $_SERVER['REQUEST_URI'];
  $len = strlen($uri);
  $cnt = 0;
  $i   = 0;

  while ($i < $len && $cnt < 2) {
    if ($uri[$i++] === '/') {
      ++$cnt;
    }
  }

  $identifier = array();
  $uri = parse_url(substr($uri, $i));
  $tmp = explode('/', $uri['path']);
  $i   = 0;

  while ($id = akh_get($tmp, ++$i)) {
    $identifier[] = $id;
  }

  $uri['path'] = array(
    'resource'   => akh_get($tmp, 0),
    'identifier' => $identifier,
  );

  if (isset($uri['query'])) {
    $tmp = explode('&', $uri['query']);
    $len = count($tmp);
    $i   = 0;

    $uri['query'] = array();
    while ($i < $len) {
      $tmp2 = explode('=', $tmp[$i++]);
      $uri['query'][akh_get($tmp2, 0)] = akh_get($tmp2, 1);
    }
  }

  return $uri;
}

function rip_parse_output($data, $encoding = null) {
  if(empty($encoding)) {
    global $config;

    $encoding = akh_get_recursive($config, array('results', 'encoding'), 'json');
  }

  switch ($encoding) {
    case 'bson':
      return 'not supported yet';
    case 'json':
      return json_encode($data);
    case 'jsonp':
      //TODO give the possibility to customize callback name
      return 'callback(' . json_encode($data) . ')';
    case 'xml':
      return 'not supported yet';
    default:
      watchdog(t('Encoding not supported'), WATCHDOG_INFO);
      exit(WATCHDOG_ERROR);
  }
}

function rip_validate_resource($uri) {
  global $db_map;

  return in_array(akh_get_recursive($uri, array('path', 'resource')), $db_map);
}

function rip_get_primary_key($table_name) {
  global $dbh;

  $primary_keys = array();

  $result = $dbh->query("DESCRIBE $table_name", PDO::FETCH_ASSOC);

  foreach ($result as $column) {
    if (akh_get($column, 'Key') === 'PRI') {
      $primary_keys[] = akh_get($column, 'Field');
    }
  }

  return $primary_keys;
}

?>
